
<template>
    <Card>
      <Row class="search-box">
        <Input placeholder="角色名称" v-model="roleName" clearable style="width:auto" @on-enter="getDataList"/>
        <Button type="default" @click="getDataList">查询</Button>
        <Button type="primary" @click="openModal()">新增</Button>
        <Button type="error" @click="confirmModal()" :disabled="dataListSelections.length <= 0">批量删除</Button>
      </Row>
      <Row>
          <Table border ref="selection" :columns="col" :data="tableData" @on-selection-change="selectionChangeHandle"></Table>
      </Row>
      <Row>
        <Page class="page-info" :total="total" :page-size="pageSize" :current.sync="pageNum" show-elevator show-total @on-change="getDataList" size="small"/>
      </Row>
       <Modal v-model="modal.isShow" draggable scrollable :title="modal.type?'新增角色':'修改角色'">
         <Form :model="modal.data" label-position="left" :label-width="70" :rules="rules" ref="roleForm">
            <FormItem label="角色名称" prop="roleName">
                <Input v-model="modal.data.roleName" placeholder="角色名称"/>
            </FormItem>
            <FormItem label="备注">
                <Input v-model="modal.data.remark" placeholder="备注"/>
            </FormItem>
            <FormItem label="授权" prop="auth">
                <Tree :data="modal.tree" show-checkbox ref="menuTree"></Tree>
            </FormItem>
        </Form>
        <div slot="footer">
            <Button  @click="modal.isShow=false">关闭</Button>
            <Button type="primary" @click="handleSubmit('roleForm')" >保存</Button>
        </div>
      </Modal>
    </Card>
</template>
<script>
import { getRoleList, getMenus, saveOrUpdateRole, deleteRoles, getRoleMenus } from '@/api/user'
import { PAGESIZE } from '@/config/baseConfig.js'
import { treeDataTranslate } from '@/libs/util.js'
import './list.less'

export default {
  data () {
    return {
      roleName: '',
      tableData: [],
      dataListSelections: [],
      total: 0,
      pageNum: 1,
      pageSize: PAGESIZE,
      modal: {
        isShow: false,
        type: true, // true新增false修改
        data: {},
        tree: []
      },
      col: [
        {
          type: 'selection',
          width: 50,
          align: 'center'
        },
        {
          title: 'ID',
          key: 'roleId',
          width: 60,
          align: 'center'
        },
        {
          title: '角色名称',
          key: 'roleName',
          align: 'center'
        },
        {
          title: '备注',
          key: 'remark',
          align: 'center'
        },
        {
          title: '创建时间',
          key: 'createTime',
          align: 'center'
        },
        {
          title: '操作',
          key: 'action',
          width: 150,
          align: 'center',
          render: (createElement, params) => {
            return createElement('div', [
              createElement('Button', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => this.openModal(params.row)
                }
              }, '修改'),
              createElement('Button', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                on: {
                  click: () => this.confirmModal(params.row.roleId)
                }
              }, '删除')
            ])
          }
        }
      ],
      rules: {
        roleName: [{ required: true, message: '角色名称不能为空!', trigger: 'blur' }],
        auth: [{ validator: this.checkedMenu, trigger: 'blur' }]
      }
    }
  },
  created: function () {
    this.getDataList()
  },
  methods: {
    async getDataList () {
      let data = await getRoleList(this.roleName, this.pageNum, this.pageSize)
      if (data.code === 200) {
        this.dataListSelections = []
        this.total = data.page.totalCount
        this.pageNum = data.page.currPage
        this.tableData = data.page.list
      }
    },
    openModal (item) {
      this.$refs['roleForm'].resetFields()
      this.modal.type = item === undefined
      this.modal.data = this.modal.type ? {} : JSON.parse(JSON.stringify(item)) // 深拷贝
      this.treeDataTranslate()
      this.modal.isShow = true
    },
    selectionChangeHandle (val) {
      this.dataListSelections = val
    },
    handleSubmit (name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          this.saveOrUpdate()
        }
      })
    },
    async saveOrUpdate () {
      let res = await saveOrUpdateRole(this.modal.data, this.modal.type, this.$refs['menuTree'].getCheckedNodes())
      if (res.code === 200) {
        this.modal.isShow = false
        this.getDataList()
      }
    },
    confirmModal (id) {
      this.$Modal.confirm({
        title: '提示',
        content: '确定删除该数据',
        onOk: () => {
          const ids = []
          if (id === undefined) {
            this.dataListSelections.map(item => ids.push(item.roleId))
          } else {
            ids.push(id)
          }
          this.deleteItem(ids)
        }
      })
    },
    async deleteItem (ids) {
      const res = await deleteRoles(ids)
      if (res.code === 200) {
        this.pageNum = 1
        this.getDataList()
      }
    },
    async treeDataTranslate () {
      let allMenus = await getMenus()
      let roleInfo = {}
      if (this.modal.data.roleId !== undefined) {
        roleInfo = await getRoleMenus(this.modal.data.roleId)
      }
      allMenus = treeDataTranslate(allMenus.menuList, 'menuId', 'parentId', roleInfo.menuIdList)
      this.modal.tree = allMenus
    },
    checkedMenu (rule, value, callback) {
      const checkedNode = this.$refs['menuTree'].getCheckedNodes()
      if (checkedNode === undefined || checkedNode.length === 0) {
        callback(new Error('请勾选权限!'))
      } else {
        callback()
      }
    }
  }
}
</script>
